// 列表页逻辑
// 0.获取元素
const onBox = document.querySelector('.on_off>.on');
const offBox = document.querySelector('.on_off>.off');
const regBox = document.querySelector('.regi');
const inp = document.querySelector('.search>input');
const ul = document.querySelector('.search>ul');
const categoryUl = document.querySelector('.mold>ul');
const goodsUl = document.querySelector('.sort>ul');
const baby = document.querySelector('.all');
const price_collection = document.querySelector('.price_collection');

const pri = document.querySelector('.sorttype');
const priceInps = document.querySelectorAll('.price>input');
const shaixuanBox = document.querySelectorAll('.shaixuan');

const pagination = document.querySelector('.pagination');

const totalBox = document.querySelector('.total')
const currentBox = document.querySelector('.current');

const pageInp = document.querySelector('.pagination input');


//1.登录检测
loginTest();
async function loginTest() {
    const id = window.localStorage.getItem('id');
    const token = window.localStorage.getItem('token');
    if(!id || !token) {
        window.localStorage.setItem('url', 'list');
        window.location.href = './login.html';
        return;
    }
    // 发送请求，检测token的有效性
    const res = await pAjax({
        url: 'http://localhost:8888/users/info',
        data: `id=${id}`,
        dataType:'json',
        token,
    })
    if(res.code === 1) {
       offBox.classList.remove('active');
       onBox.innerText = res.info.nickname;
       onBox.classList.add('active');
       regBox.style.visibility = 'hidden';
    }else{
        window.localStorage.setItem('url', 'list');
        window.location.href = './login.html';
        return;
    }
 
}

//2.搜索引擎  
inp.addEventListener('input', () => {
    const text = inp.value;
    const script = document.createElement('script');
    script.src = "https://suggest.taobao.com/sug?code=utf-8&q=" + text + "&_ksTS=1624112642752_267&callback=jp&k=1&area=c2c&bucketid=8";
    document.body.appendChild(script);
    script.remove();
})
function jp(res) {
    console.log(res)
    if(res.result.length === 0){
        ul.style.display = 'none';
        return;
    }
    let str = '';
    res.result.forEach(item => {
        str += `<li>${item[0]}</li>`
    })
    ul.innerHTML = str;
    ul.style.display = 'block';

}


//3.显示/收起筛选
$('.shouqi').click( function(){
    $(this).parent().nextAll().slideToggle();
})




//5.获取商品列表，渲染页面
let listinfo = {
   page: 1,
   sort: 'pop',
   action: 'skirt' ,
}


getGoodsList();
function getGoodsList() {
    const script = document.createElement('script');
    script.src="https://list.mogu.com/search?callback=goods&_version=8193&ratio=3%3A4&cKey=15&page=" + listinfo.page + "&sort=" + listinfo.sort + "&ad=0&fcid=&action=" + listinfo.action + "&ptp=31.KbeT9.0.0.rHNA1k3O&cpc_offset=0&offset=&_=1624362711194";
    document.body.appendChild(script);
    script.remove();
    
}
// 准备一个函数，接受jsonp返回的数据
function goods(res) {
    console.log(res);
    const {result} = res;
    const goodsData = result.wall.docs;
    // console.log(res);
    // 渲染列表
    let str = '';
    goodsData.forEach(item => {
       str += `
        <li class="girl" data-id="${item.tradeItemId}">
            <div class="pic">
                <img src="${item.img}" alt="">
            </div>
            <div class="desc">
                <div class="info">
                    <p class="price">￥<span>${item.price}</span></p>
                    <p class="baoyou">包邮</p>
                    <p class="purse"><span>${item.sale}</span>人付款</p>
                </div>
                <div class="title">${item.title}</div>
                <div class="shop">
                    <p class="iconfont icon-gengduo-2"></p>
                    <p>空城计旗舰店</p>
                    <p>浙江&nbsp;杭州</p>
                </div>
                <div class="best_sallers">
                    <p class="adi">掌柜热卖</p>
                    <p><img src="./img/TMT.jpeg" alt=""></p>
                    <p><img src="./img/WW.jpeg" alt=""></p>
                </div>
            </div>
            
        </li>
       ` 
    })
    goodsUl.innerHTML = str;
    
    // 渲染价格
    const price = result.priceList;
    // console.log(price)
    let s = ''
    price.forEach(item => {
        s += `
        <span class="price_span">${item.min}-${item.max}</span>
        `
    })
    price_collection.innerHTML = s;

    // 分页信息
    const totalcount = result.wall.pager.total;
    const perpage = result.wall.pager.perPage;
    totalBox.innerText = Math.ceil(totalcount / perpage); 
}
    



//6.点击事件
baby.addEventListener('click', e => {
    e = e || window.event;
    const target = e.target || e.srcElement;
    // 判断点击的是价格span
    if(target.className === 'price_span') {
        const priceData = target.innerText.split('-');
        priceInps[0].value =   priceData[0];
        priceInps[1].value =   priceData[1]; 
        const script = document.createElement('script');
       
        // script.src="https://list.mogu.com/search?callback=goods&_version=8193&ratio=3%3A4&cKey=15&page=" + listinfo.page + "&sort=" + listinfo.sort + "&ad=0&fcid=50240&action=" + listinfo.action + "&acm=3.mce.1_10_1ko4s.132244.0.myVdrsB3SVglH.pos_871-m_482170-sd_119&ptp=31.v5mL0b._head.0.9EtcaWqs&minPrice=" + priceInps[0].value + "&maxPrice=" + priceInps[1].value + "&cpc_offset=0&offset=&_=1624371637034";
        script.src="https://list.mogu.com/search?callback=goods&_version=8193&ratio=3%3A4&cKey=15&page=" + listinfo.page + "&sort=" + listinfo.sort + "&ad=0&action=" + listinfo.action + "&minPrice=" + priceInps[0].value + "&maxPrice=" + priceInps[1].value + "&cpc_offset=0&offset=&_=1624371637034";

        document.body.appendChild(script);
        script.remove();
    }
    // 判断点击的是button
    if(target.tagName === 'BUTTON') {
        const minPrice = priceInps[0].value;
        const maxPrice = priceInps[1].value;
        console.log(minPrice,maxPrice)
        const script = document.createElement('script');
       
        // script.src="https://list.mogu.com/search?callback=goods&_version=8193&ratio=3%3A4&cKey=15&page=" + listinfo.page + "&sort=" + listinfo.sort + "&ad=0&fcid=50240&action=" + listinfo.action + "&acm=3.mce.1_10_1ko4s.132244.0.myVdrsB3SVglH.pos_871-m_482170-sd_119&ptp=31.v5mL0b._head.0.9EtcaWqs&minPrice=" + priceInps[0].value + "&maxPrice=" + priceInps[1].value + "&cpc_offset=0&offset=&_=1624371637034";
        script.src="https://list.mogu.com/search?callback=goods&_version=8193&ratio=3%3A4&cKey=15&page=" + listinfo.page + "&sort=" + listinfo.sort + "&ad=0&action=" + listinfo.action + "&minPrice=" + minPrice + "&maxPrice=" + maxPrice + "&cpc_offset=0&offset=&_=1624371637034";
        document.body.appendChild(script);
        script.remove();
    }
    //判断点击的是商品类型
    if(target.className === 'gType') {
        listinfo.action = target.dataset.skey;
        getGoodsList();
        for(let i = 0; i<categoryUl.children.length; i++) {
            categoryUl.children[i].classList.remove('active');
        }
        target.classList.add('active');

    }
    // 判断点击的是筛选条件
    if(target.className === "shaixuan") {
        // console.log(target)
        listinfo.sort = target.dataset.condition;
        getGoodsList()
        for(let i = 0; i<shaixuanBox.length; i++) {
            shaixuanBox[i].classList.remove('active');
        }
        target.classList.add('active');

    }
})


// 7.分页功能
let currentpage = 1;
// 绑定点击事件
console.log(pagination)
pagination.addEventListener('click', e => {
    e = e || window.event;
    const target = e.target || e.srcElement;
    // 判断点击的是上一页
    if(target.className === 'prev') {
        if(currentpage === 1) return;
        currentpage --;
        currentBox.innerText = currentpage;
        listinfo.page = currentpage;
        getGoodsList()
    }
    // 判断点击的是下一页
    if(target.className === 'next') {
        if(currentpage === totalBox.innerText) return;
        currentpage ++;
        currentBox.innerText = currentpage;
        listinfo.page = currentpage;
        getGoodsList()
    } 
})


//8.具体到某一页
console.log(pageInp)
pageInp.onchange = function() {
    const cPage = pageInp.value;
    currentpage = cPage;
    currentBox.innerText = currentpage;
    listinfo.page = currentpage;
    getGoodsList();

}




// 9.跳转详情页

goodsUl.addEventListener('click', e => {
    e = e || window.event;
    const target = e.target || e.srcElement;
    if(target.tagName === 'LI') {
        const id = target.dataset.id;
        const img_url = target.firstElementChild.firstElementChild.src;
        const title = target.children[1].children[1].innerText;
        const info_node = target.children[1].firstElementChild;
        const price = info_node.firstElementChild.firstElementChild.innerText
        const sale = info_node.lastElementChild.firstElementChild.innerText;
        const infoArr = JSON.parse(window.localStorage.getItem('infoArr')) || [];
        const good = infoArr.find(item => item.id === id);
        if(!good){
            var info = {
                id,
                img_url,
                title,
                price,
                sale,
            }
            infoArr.push(info)
        }
        window.localStorage.setItem('infoArr', JSON.stringify(infoArr));
        window.localStorage.setItem('goodsId', id);
        window.location.href = './detail.html';
    }
    
})

